
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

struct ThreadData
{
    sockaddr_in server;
    int sockfd;
    string serverip;
};
void Usage(string proc)
{
    cout << "\n\rUsage: " << proc << " serverip serverport\n"
         << endl;
}
void *receive_message(void *args)
{
   // dup(,2);

    ThreadData *td = static_cast<ThreadData *>(args);
    char buffer[1024];
    while (true)
    {
        memset(buffer, 0, sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t lent = sizeof(temp);
        ssize_t s = recvfrom(td->sockfd, buffer, 1023, 0, (sockaddr *)&temp, &lent);
        if (s > 0)
        {
            buffer[s] = 0;
            cerr << buffer << endl;
        }
    }
}
void *send_message(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    string messages;

    string message = td->serverip + "coming.....";
    cout<<message<<endl;
    socklen_t len = sizeof(td->server);
    sendto(td->sockfd, message.c_str(), message.size(), 0, (sockaddr *)&(td->server), len);

    while (true)
    {
        getline(cin, messages);
        sendto(td->sockfd, messages.c_str(), messages.size(), 0, (sockaddr *)&(td->server), len);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    ThreadData *td = new ThreadData();
    td->serverip = argv[1];              // ip地址
    uint64_t serverport = stoi(argv[2]); // 端口
    td->server.sin_family = AF_INET;
    td->server.sin_port = htons(serverport);
    td->server.sin_addr.s_addr = inet_addr(td->serverip.c_str());
    socklen_t len = sizeof(td->server);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cout << "socket created failed";
        return 1;
    }
    td->sockfd = sockfd;
    pthread_t sendtid;
    pthread_t receivetid;
    pthread_create(&sendtid, nullptr, send_message, td);
    pthread_create(&receivetid, nullptr, receive_message, td);
    pthread_join(sendtid, nullptr);
    pthread_join(receivetid, nullptr);

    delete td;
    close(sockfd);
}